import json
import re

import requests
from django import http
from django.http import JsonResponse, HttpResponse

from django.views import View
from pymysql import DatabaseError

from rest_framework.response import Response

from apps.users.models import User



class LoginView(View):
    # 指定视图所使用的序列化器类

    def post(self,request,*args,**kwargs):
        # 接收参数
        # 1. 获取参数并进行校验

        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        print(username,pwd)
        if not all([username, pwd]):
            return http.HttpResponseBadRequest('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{3,20}$', pwd):
            return http.HttpResponseBadRequest('请输入6-20位的密码')

        try:
            user = User.objects.create(username=username, password=pwd)
        except DatabaseError:
            return http.HttpResponseBadRequest('数据保存失败')


        # 注册时用户名写入到cookie，有效期15天
        # response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        # #
        # return response
        data={
            'username':user.username,
            'pwd':user.password
        }

        return JsonResponse( data,content_type='application/json')




